<?php
require_once( '../system/smarty.inc' );
require_once( '../system/mdao/Class_D_DNPW_AREA.php' );
require_once( '../system/mdao/Class_M_PATTERN.php' );
require_once( '../system/mdao/Class_D_DNPW_AREA_SHOP.php');
require_once( '../system/mdao/Class_M_OTHER.php' );
require_once( '../system/tdao/Class_T_MON_CELL.php' );
require_once( '../system/Class_ERROR.php' );
require_once( '../system/Class_PWD.php' );
require_once( '../system/login.inc.php' );

Class_PWD::valid_auth(AOKI_AUTH_DNP_AREA, $login['staff_auth']);

$editflg = 1; //1 編集可能　2 部数だけ編集可能
$is_shop = 2; //1 店舗可能　2　店舗不可
 
$isG5 = FALSE ;

if   ($login['staff_auth'] == 'G-5') {
	if( isset($_GET['isshop']) && $_GET['isshop'] != '' ){
		echo "アクセス不可";
		exit;
	}
	$isG5 = TRUE ;
	$editflg = 2;
}

$dao  = new Class_D_DNPW_AREA ;
$dao_mg  = new Class_T_MON_CELL($dao->get_db());
if( $_SERVER['REQUEST_METHOD'] == 'GET' ){
	$phase = 'input';
	if ( isset($_GET['w']) && $_GET['w'] != '' ){
		$dao->setTableNameWeek($_GET['w']);
		$dao_mg->setTableNameWeek($forms['w']);
		$matrix_cd = $_GET['w'] ;
		
		$titledata = Class_M_OTHER::get_titles( $matrix_cd,$_GET['p'] );
		foreach ($titledata as $k => $v) {
			$titledata[$k]["irgyunm"] = $aoki_map_sort[ $v["map"] ];
		}
		
		$wData     = Class_M_OTHER::get_by_matrix_cd( $matrix_cd );
		$dispweek = $wData["year4"].'年'.$wData["week_cd"].'週';
		if ( $wData["[week_seq"] ) {
			$dispweek = $dispweek."回";
		}
		
		$dispweek = $dispweek."(". Class_PWD::int8_to_date($wData["flier_date"]) .")";
		
	}else {
		echo "パターンエラー";
		exit;
	}
	$forms             = $dao->get( $_GET['id'] );
	$titelSort         = $titledata[$forms["title_cd"]]["map"];
	$forms["isirgyu"]  = $aoki_map_sort[$titelSort];
	//$dists  =  Class_M_OTHER::get_dist_array( );
	//$hands  =  Class_M_OTHER::get_hand_array( );
	//print_r($hands);
	//$forms["dist_name"] = $dists[$forms["dist_id"]];
	//$forms["hand_name"] = $hands[ $forms["hand_cd"] ];
	
	$daoadshop = new Class_D_DNPW_AREA_SHOP($dao->get_db());
	$daoadshop ->setTableNameWeek($_GET['w']);
	//$disp_ng = $forms["disp_ng"]?$forms["disp_ng"]:0;
	$titelSort = NULL;
	if ($forms["title_cd"]) {
		$titelSort = $titledata[$forms["title_cd"]]["map"];
	}
	
	if  ($titelSort){
		$dbarray = $dao->getPATShops($_GET['id'], $forms["pattern_cd"],$titelSort );
	}else {
		$dbarray = $dao->getPATShops($_GET['id'], $forms["pattern_cd"]);
	}
	//print_r($dbarray);
	
	//データ整形
	foreach ($dbarray as $k=>$v) {
		$forms["mutirow"] []=array("shop_cd"=> $v["shop_cd"], 
			"ins_nums"  => $v["ins_count"],
			"zone"      => $v["zone"], 
			"area"      => $v["area"],
			"shop_name" => $v["shop_name"], 
			"map_no"    => $v["map_no"],
			"year_sale" => $v["year_sale"], 
			"shop_per"  => $v["shop_per"],
			"shop_nums" => $v["shop_nums"]);
	}
	
	$pdao = new Class_M_PATTERN ;  
	if ( isset($_GET['p']) && $_GET['p'] != '' ){
		if ( $patterns  = $pdao->get( $_GET['p'] ) ) {
			$forms["pattern_cd"]   =  $patterns["pattern_cd"];
			$forms["pattern_name"] =  $patterns["pattern_name"];
		}
	}else {
		echo "パターンエラー";
		exit;
	}
	

}else{
	$forms      =  $_POST;
	$matrix_cd  =  $forms['w'] ;
	$dao->setTableNameWeek($forms['w']);
	$dao_mg->setTableNameWeek($forms['w']);
	
	if( $forms['mode'] == 'del' ){
		try {
			$daoadshop =new Class_D_DNPW_AREA_SHOP($dao->get_db());
			$daoadshop ->setTableNameWeek($forms['w']);
			$dao->begin_trans();
			$del_success = false;
			if ($dao->del("  id = '{$forms['id']}' ")) {
				$del_success = true;
			}
			
			$where = sprintf(" dnpid =  '%s' ", $forms['id'] );
			if ( $daoadshop->del($where) ) {
				$del_success = true;
			}
			
			
			$where = " matrix_cd =  {$matrix_cd} and pattern_cd = {$forms['pattern_cd']} and title_cd = {$forms['title_cd']} AND qtype > 0";
			if ( $dao_mg->delAreaTitle($where) ) {
				$del_success = true;
			}
			
			 
			
			if ($del_success) {
				$dao->commit_trans();
				$smarty->assign('message', 'セールタイトル削除が完了しました。');
			} else {
				$dao->rollback_trans();
				$smarty->assign('message', 'セールタイトル削除が失敗しました。');
			}
		} catch (Exception $e) {
				$dao->rollback_trans();
				$smarty->assign('message', 'ＤＢエラーで削除は失敗しました。');
		}
		
		if( isset( $forms ) ) $smarty->assign('forms', $forms);
		$smarty->assign('phase', "deleted" );
		$smarty->assign('menu', $smarty->fetch('menu.html') );
		$smarty->assign('logout', $smarty->fetch('logout.html') );
		$smarty->assign('footer', $smarty->fetch('footer.html') );
		
		$smarty->display('ddnpwarea_form_pat2.html');
		exit;
	}
	
	
	$data_mg = $dao_mg->getMatrixTerm( $matrix_cd);
	
	$statusID   = Class_PWD::getMatrixStatues( $data_mg );
	
	//echo "**".$is_shop."**";
	if (isset($forms["shop_cd"])) {
		foreach ($forms["shop_cd"] as $k=>$v) {
			$forms["mutirow"] []=array("shop_cd"=> $v,
				"shop_name"  => $forms["shop_name"][$k], 
				"year_sale"  => $forms["year_sale"][$k], 
				"map_no"     => $forms["map_no"][$k],
				"shop_nums"  => $forms["shop_nums"][$k],
				"area"       => $forms["area"][$k],
				"zone"       => $forms["zone"][$k],
				"ins_nums"   => $forms["ins_nums"][$k]);
		}
	} 
	$titledata =  Class_M_OTHER::get_titles($forms['w'], $forms["pattern_cd"] );
		foreach ($titledata as $k => $v) {
			$titledata[$k]["irgyunm"] = $aoki_map_sort[ $v["map"] ];
		}
	if( $forms['mode'] == 'input' ){
		
		$err     = new Class_ERROR;
		$chk     = $dao->getPATChecks();
		
		foreach ($chk as $kcol => $chkval) {
			$err_mes[$kcol]  = $err->check( $forms[$kcol], $chkval );
		}
		$index = 0;
		$daoadshop =new Class_D_DNPW_AREA_SHOP($dao->get_db());
		
		$daoadshop ->setTableNameWeek($forms['w']);
		$chkadshop     = $daoadshop->get_checks();
	
		
		foreach($forms["mutirow"] as $k=>$v) {
			//$err_mes["shop_per"][$index]   = $err->check( $v["shop_per"],  $chkadshop["shop_per"] );
			$err_mes["shop_nums"][$index]  = $err->check( $v["shop_nums"], $chkadshop["shop_nums"] );
			$index = $index + 1;
		}
		//$forms["dist_id"]           =  Class_M_OTHER::get_dist_id($forms["dist_name"]);
		
		if( $forms['id'] != '' ){
			$err_mes["mutirow"] = $err->check( $forms["mutirow"],array( "EXIST" ));
			$where = sprintf(" pattern_cd = '%s' and title_cd  = '%s'  and id <> '%s'", $forms['pattern_cd'], $forms["title_cd"], $forms['id'] );
			if ( $dao->exits($where) ) {
					$err->clear = false;
					$err_mes['title_cd'] = '<p class="error">このパターンタイトルは重複しています</p>';
				}
		}else {
			if( $err_mes['title_cd'] == '' ){
				$where = sprintf(" pattern_cd = '%s' AND title_cd ='%s' ", $forms['pattern_cd'], $forms["title_cd"] );
				if ( $dao->exits($where) ) {
					$err->clear = false;
					$err_mes['title_cd'] = '<p class="error">このパターンタイトルは重複しています</p>';
				}
			}
		}
		foreach($forms["mutirow"] as $k=>$v) {
			if (empty($v["map_no"])) {
					$err->clear = false;
					$err_mes['grid'] = '<p class="error">一覧のマップNoは存在しないので、更新できないです。</p>';
			}
		}
		
		$is_final = FALSE;
		$login_auth = $login['staff_auth'];
		
		$can_edit = FALSE;
		$edit_msg = "編集権限がありません";

		//if (($login_auth == 'G-0') || ( $login_auth== 'G-1') ||  ($login_auth == 'G-2')) {
		switch ( $statusID ) {
			case AOKI_MATRIXS_DRAFT_CREATE:
			case AOKI_MATRIXS_DRAFT_MODIFY:
			case AOKI_MATRIXS_FINAL_MODIFT:
			//if ( $login_auth == 'G-1' ) {
					$edit_msg = "";
					$can_edit = TRUE;
			//}
				break;
				
			case AOKI_MATRIXS_DRAFT_INPUT:
			case AOKI_MATRIXS_FINAL_INPUT:
				//if ( ( $login_auth == 'G-2' )  ) {
					$edit_msg = "";
					$can_edit = TRUE;
				//}
				break;
				
			case AOKI_MATRIXS_FINAL_END:
				//if ( $login_auth == 'G-1' ) {
					//$edit_msg = "FINAL手配済みのデータです";
					$edit_msg = "";
					$can_edit = TRUE; 			
				//}
				break;
			
			default:
				$edit_msg = "編集期限外です(ステータス：".$aoki_matrix_status[$statusID].") " ;
				break;
		}
		
		switch ( $statusID ) {
			case AOKI_MATRIXS_FINAL_INPUT:
			case AOKI_MATRIXS_FINAL_MODIFT:
			case AOKI_MATRIXS_FINAL_END:
				$is_final = TRUE;
				break;
		}
		$is_final = TRUE;
		if ($edit_msg){
			$err->clear = false;
			$err_mes['weekmsg'] = '<p class="error">'.$edit_msg.'</p>';
		}
		if( $err->clear ){
			if( $forms['id'] == '' ){
				try {
					$dao->begin_trans();
					$executeflg = TRUE;
					$values = array();
					$values["pattern_cd"]   =  $forms["pattern_cd"] ;
					$values["title_cd"]     =  $forms["title_cd"] ;
					
					$values["dnpid"]        =  0 ;
					
					//if (!["dist_id"]){
					//	$values["dist_id"]         =  Class_M_OTHER::do_dist($forms["dist_name"]);
					//}
					//			$hand_name = '大日本印刷';
					//class_M_OTHER::do_area($values["area_name"]);
					$values["hand_cd"]           =   Class_M_OTHER::do_hand('大日本印刷');
					$values["area_nums"]         =  $forms["area_nums"];
					$values["center_flg"]        =   0;
					
					if ($dnpid =  $dao->add($values)) {
						foreach($forms["mutirow"] as $kk=>$vv) {
							$shopval["dnpid"]         = $dnpid ;
							$shopval["shop_cd"]       = $vv["shop_cd"] ;
							$shopval["pattern_cd"]     = $forms["pattern_cd"] ;
							$shopval["shop_per"]      = 0;
							$shopval["shop_nums"]     = $vv["shop_nums"] ;
							$shopval["ins_nums"]      = $vv["ins_nums"] ;
							if ($daoadshop->add0($shopval)) {
							} else {
								$executeflg = FALSE;
								break;
							}
						}
					} else {
						$executeflg = FALSE;
					}
					if  ($executeflg) {
						$titles = $titledata[ $forms["title_cd"] ];
						$pattern_cd = $forms["pattern_cd"];
						$paras["pattern_cd"]  =  $pattern_cd;
						$celldatas = array();
						foreach($forms["mutirow"] as $k=>$v) {
							$celldata = array();
							$celldatarow = array();
							$shopcd  = $v["shop_cd"];
							$celldatarow["matrix_cd"] = $matrix_cd;
							$celldatarow["shop_cd"]   = $shopcd;
							
							$celldata["shop_cd"] = $shopcd;
							$celldata["pnums"]  =  $v["shop_nums"];
							$celldata["map_no"]  =  $v["map_no"];
							$celldata["isirgyu"]  = $titles["map"] ;
							$celldata["pattern_cd"]  = $pattern_cd ;
							$celldata["sample"]  = 0 ;
							$celldata["qtype"]   = $dao->getLnewsNo($shopcd,$pattern_cd ) ;
							$celldata["wtype"]   = 9 ;
							$celldata["matrix_cd"] = $matrix_cd ;
							$celldata["title_cd"]  = $forms["title_cd"] ;
							$celldata["title"]     = $titles["titlecell"] ;
							$celldata["size"]      = $titles["size"] ;
							$celldatarow["detail"][$shopcd]  = $celldata;
							$celldatas[$shopcd] =  $celldatarow;
						}
						if ( !$dao_mg->dosave(TRUE, $celldatas, $matrix_cd, $is_final, NULL, $pattern_cd, $forms["title_cd"]) ) {
							$executeflg  = FALSE;
						}
					}
					if ($executeflg) {
						$dao->commit_trans();
						$smarty->assign('message', '登録が完了しました。');
					} else {
						$dao->rollback_trans();
						$smarty->assign('message', '登録が失敗しました。');
					}
				} catch (Exception $e) {
						$dao->rollback_trans();
						$smarty->assign('message', 'ＤＢエラーで失敗しました。');
				}
			}else{
				/*更新か削除かチェック整形*/
				$dataadd  = array();
				$datadel  = array();
				$dataedit = array();
				try {
					$executeflg = TRUE;
					$dao->begin_trans();
					$values = array();
					
					$values["pattern_cd"]        =  $forms["pattern_cd"];
					
					//if (!$forms["dist_id"]){
						//$values["dist_id"]         =  Class_M_OTHER::do_dist($forms["dist_name"]);
					//}
					//
					//$values["hand_cd"]           =  Class_M_OTHER::do_hand($forms["hand_name"]);
					$values["title_cd"]         =  $forms["title_cd"];
					$values["area_nums"]         =  $forms["area_nums"];
					$values["center_flg"]        =    0;
					
					$values["memo"]         =  $forms["memo"];
					
					if ($dao->edit( $forms['id'], $values )) {
						/*
						if ($dao->updateShopNums( $forms['id'], $values["area_nums"])) {
							$executeflg = TRUE;
						}else {
							$executeflg = FALSE;
						}
						
						if ( $forms["center_flg"] == "1" || $forms["hcenter_flg"] == "1"  ) {
							$centerSum =  $forms["c_area_nums"]  ;
							
							if ( $forms["center_flg"] == "1" ){
								$centerSum =  $centerSum + $forms["area_nums"];
							}
							if  (!($dao->updateCenterShops($forms["pattern_cd"], $centerSum))){
								$executeflg = FALSE;
							}
						}
						*/
					} else {
						$executeflg = FALSE;
					}
					//店舗DBの更新
					if ($executeflg){
						//$disp_ng = $forms["disp_ng"]?$forms["disp_ng"]:0;
						$wherearr[] = sprintf(" dnpid =  '%s' ", $forms['id'] );
						$dbarray = $daoadshop->search($wherearr );
						//削除.更新のデータ作成
						foreach($dbarray as $k=>$v) {
							$delflg = TRUE;
							$val_shop_nums = "0";
							$val_shop_per  = "0";
							$val_ins_nums  = "0";
							foreach($forms["mutirow"] as $kk=>$vv) {
								if ($v["shop_cd"] == $vv["shop_cd"] ) {
									$delflg = FALSE;
									$val_shop_nums =  $vv["shop_nums"];
									$val_ins_nums  =  $vv["ins_nums"];
									$val_shop_per  =  0;
									break;
								}
							}
							if ($delflg){
								if ($daoadshop->remove($v["id"])) {
								} else {
									$executeflg = FALSE;
								}
							} else {
								$values = array();
								$values["shop_nums"] = $val_shop_nums;
								$values["ins_nums"]  = $val_ins_nums;
								$values["shop_per"]  = 0;
								if ($daoadshop->edit( $v["id"] ,$values)) {
								} else {
									$executeflg = FALSE;
								}
							}
						}
						//追加のデータ作成
						foreach($forms["mutirow"] as $k=>$v) {
							$taddflg = TRUE;
							foreach($dbarray as $kk=>$vv) {
								if ($v["shop_cd"] == $vv["shop_cd"] ) {
									$taddflg = FALSE;
									break;
								}
							}
							if ($taddflg){
								$values = array();
								$values["dnpid"]           = $forms['id'];
								$values["shop_cd"]         = $v["shop_cd"] ;
								$values["pattern_cd"]      =  $forms["pattern_cd"];
								$values["shop_per"]        = 0 ;
								$values["shop_nums"]       = $v["shop_nums"] ;
								$values["ins_nums"]        = $v["ins_nums"] ;
								if ($daoadshop->add0($values)) {
								} else {
									$executeflg = FALSE;
								}
							}
						}
					}
					if  ($executeflg) {
						$titles = $titledata[ $forms["title_cd"] ];
						$pattern_cd = $forms["pattern_cd"];
						$paras["pattern_cd"]  =  $pattern_cd;
						$celldatas = array();
						foreach($forms["mutirow"] as $k=>$v) {
							$celldata = array();
							$celldatarow = array();
							$shopcd  = $v["shop_cd"];
							$celldatarow["matrix_cd"] = $matrix_cd;
							$celldatarow["shop_cd"]   = $shopcd;
							
							$celldata["shop_cd"] = $shopcd;
							$celldata["pnums"]  =  $v["shop_nums"];
							$celldata["map_no"]  =  $v["map_no"];
							$celldata["isirgyu"]  = $titles["map"] ;
							$celldata["pattern_cd"]  = $pattern_cd ;
							$celldata["sample"]  = 0 ;
							$celldata["qtype"]   = $dao->getLnewsNo($shopcd,$pattern_cd ) ;
							$celldata["wtype"]   = 9 ;
							$celldata["matrix_cd"] = $matrix_cd ;
							$celldata["title_cd"]  = $forms["title_cd"] ;
							$celldata["title"]     = $titles["titlecell"] ;
							$celldata["size"]      = $titles["size"] ;
							$celldatarow["detail"][$shopcd]  = $celldata;
							$celldatas[$shopcd] =  $celldatarow;
						}
						if ( !$dao_mg->dosave(TRUE, $celldatas, $matrix_cd, $is_final, NULL, $pattern_cd, $forms["title_cd"]) ) {
							$executeflg  = FALSE;
						}
					}
					if  ($executeflg) {
						$dao->commit_trans();
						$smarty->assign('message', '更新が完了しました。');
					} else {
						$dao->rollback_trans();
						$smarty->assign('message', '更新が失敗しました。');
					}
				} catch (Exception $e) {
					$dao->rollback_trans();
					$executeflg = FALSE;
					$smarty->assign('message', 'ＤＢエラーで失敗しました。');
				}
			}
			$phase = 'complete';
		}else{
			$phase = 'input';
		}
	}
}
	if(isset($forms['id']) && $forms['id'] == '' ) {
		$editflg  = 1;
	}
	
	$smarty->assign('editflg', $editflg);
	$smarty->assign('isshop', $is_shop);
	
	//print_r( $err_mes );
	$forms["w"]      = empty( $forms["w"]  )? $matrix_cd: $forms["w"] ;
	$forms["dispw"]      = empty( $forms["dispw"]  )? $dispweek : $forms["dispw"] ;
	
	
	if ( $forms["title_cd"] ) {
			$forms["title_name"] = $titledata[ $forms["title_cd"] ]["titlecell"];
			$forms["title_size"] = $titledata[ $forms["title_cd"] ]["size"]; 
			$forms["title_sort"] = $titledata[ $forms["title_cd"] ]["map"]; 
		} else {
			$forms["title_name"] = "";
			$forms["title_size"] = ""; 
			$forms["title_sort"]  = ""; 
		}
	if( isset( $forms ) ) $smarty->assign('forms', $forms);
	if( isset( $err_mes ) ) $smarty->assign('err', $err_mes);
	
	 
	 
	 
	$smarty->assign('titledata', $titledata );
	
	$titles = array();
	$titles[0] = PLEASE_SELECT_ARR;
	foreach ($titledata as $k => $v) {
		$titles[$k] = $v["titlecell"];
	}
	$smarty->assign('titles', $titles );
		
	$smarty->assign('phase', $phase );
	$smarty->assign('menu', $smarty->fetch('menu.html') );
	$smarty->assign('logout', $smarty->fetch('logout.html') );
	$smarty->assign('footer', $smarty->fetch('footer.html') );
	
	$smarty->display('ddnpwarea_form_pat2.html');
	
	function updateCenter($dao, $inCenterFlg,  $inc_area_nums, $inarea_nums) {
		

	}
	
	
?>